package com.zh.flowable.domain.flow.listener;

import com.zh.flowable.external.EmployeeManagementService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;


/**
 * @author
 * @date 2025/8/29
 */
@Slf4j
@Component
public class ProcessStartListener implements ExecutionListener {
    private final EmployeeManagementService employeeManagementService;

    public ProcessStartListener(EmployeeManagementService employeeManagementService) {
        this.employeeManagementService = employeeManagementService;
    }

    @Override
    public void notify(DelegateExecution execution) {
        String processDefinitionId = execution.getProcessDefinitionId();
        String instanceId = execution.getProcessInstanceId();

        String[] split = processDefinitionId.split(":");
        String processKey = split[0];

        log.info("[{}]流程启动时 触发查询supervisor... instanceId: {}", processKey, instanceId);

        var applicant = (String) execution.getVariable("applicant");

        var employeeDto = employeeManagementService.getSuperiorEmployeeInfo(applicant);
        if (employeeDto != null) {
            // 设置supervisor变量
            execution.setVariable("supervisor", employeeDto.getEmpNo());
            log.debug("setVariable supervisor: {}", employeeDto.getEmpNo());
        }
    }


    /**
     * 获取员工的部门经理编号
     * @param empNo 员工编号
     * @return 部门经理编号
     */
    public String queryManagerEmployeeNo(String empNo) {
        var employeeDto = employeeManagementService.getManagerEmployeeInfo(empNo);
        if (employeeDto != null) {
            return employeeDto.getEmpNo();
        }
        return null;
    }
}
